const express = require('express');
const mysql = require('mysql2');
const app = express();

// 创建数据库连接
const connection = mysql.createConnection({
    host: process.env.DB_HOST || 'db',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '123456',
    database: process.env.DB_NAME || 'elderly_health_db',
    port: 3306
});

// 连接数据库
connection.connect(error => {
    if (error) {
        console.error('Error connecting to the database:', error);
        return;
    }
    console.log('Successfully connected to database.');
});

// 添加错误处理
connection.on('error', function(err) {
    console.error('Database error:', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') {
        connection.connect();
    } else {
        throw err;
    }
});

// 静态文件服务
app.use(express.static('public'));

// 测试数据库连接的路由
app.get('/api/test', (req, res) => {
    connection.query('SELECT * FROM users', (error, results) => {
        if (error) {
            console.error('Query error:', error);
            return res.status(500).json({ error: error.message });
        }
        res.json(results);
    });
});

const port = 3000;
app.listen(port, '0.0.0.0', () => {
    console.log(`Server running on port ${port}`);
}); 